package meijuli.com.join51.business.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jhx.common.model.DeviceInfo;
import com.jhx.common.utils.MD5Utils;
import com.jhx.common.utils.SystemUtil;
import com.jhx.common.utils.ToastUtil;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.IOException;

import meijuli.com.join51.business.MeiJuLi;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.aliyun.MD5Util;
import meijuli.com.join51.business.data.Downloader;
import meijuli.com.join51.business.model.AppBean;
import meijuli.com.join51.business.utils.LogUtils;

/**
 * 下载页面
 *
 * @author wenqin 2017-05-09 18:48
 */

public class DownloadActivity extends BaseActivity {
    private final static String KEY_APP_BEAN = "key_app_bean";
    public static final String APP_FILE_NAME = "com.join51.juhuixia.business.apk";
    TextView mToolbarTitle;
    Toolbar mToolbar;
    ProgressBar mProgressBar;
    TextView mTextProgress;
    TextView mTips;
    private AppBean mAppBean;
    private Downloader mDownloader;

    public static void start(Activity activity, AppBean appBean) {
        Intent intent = new Intent(activity, DownloadActivity.class);
        intent.putExtra(KEY_APP_BEAN, appBean);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        mToolbarTitle = findViewById(R.id.toolbar_title);
        mToolbar = findViewById(R.id.toolbar);
        mProgressBar = findViewById(R.id.progress_bar);
        mTextProgress = findViewById(R.id.text_progress);
        mTips = findViewById(R.id.tips);

        initToolBar();

        mAppBean = (AppBean) getIntent().getSerializableExtra(KEY_APP_BEAN);
        DeviceInfo deviceInfo = SystemUtil.getDeviceInfo();
        if (!"wifi".equals(deviceInfo.getNetworkType())) {
            showConfirmDialog();
        } else {
            String fileMD5 = "";
            try {
                fileMD5 = MD5Utils.fileMD5(MeiJuLi.Key.PATH_UPDATE_FILE + "/" + APP_FILE_NAME);
            } catch (IOException e) {
                e.printStackTrace();
            }
            LogUtils.i("check", "fileMD5-before: " + fileMD5 + "**" + "MD5str: " + mAppBean.getMd5());
            fileMD5 = fileMD5.toLowerCase();
            LogUtils.i("check", "fileMD5-after: " + fileMD5 + "**" + "MD5str: " + mAppBean.getMd5());
            if (mAppBean.getMd5().equals(fileMD5)) {
                installPkg(MeiJuLi.Key.PATH_UPDATE_FILE + "/" + APP_FILE_NAME);
            } else {
                download(mAppBean.getAppDown());
            }

        }

    }

    private void showConfirmDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("更新版本要消耗" + (mAppBean.getAppSize() == null ? "" : mAppBean.getAppSize())
                + "流量，建议使用wifi下载，是否继续使用流量下载？")
                .setTitle("下载提示")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        download(mAppBean.getAppDown());
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).create();
        builder.show();
    }

    private void initToolBar() {
        mToolbar.setTitle("");
        mToolbarTitle.setText("软件更新");
        mToolbar.setNavigationIcon(R.mipmap.icon_back_white);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                mDownloader.quit();
            }
        });
    }


    private void download(String url) {
        if (null == mDownloader) {
            mDownloader = Downloader.newInstance(new Downloader.OnDownloadListener() {
                @Override
                public void onDownloadFinished(String url, String path, String vfileName) {
                    mTips.setText("软件下载完成");
                    if (MD5Util.checkFileMD5(path + "/" + vfileName, mAppBean.getMd5())) {
                        installPkg(path + "/" + vfileName);
                    } else {
                        ToastUtil.getInstance().showToast(DownloadActivity.this, "安装失败");
                        String fileMD5 = MD5Util.md5(new File(path + "/" + vfileName));
                        CrashReport.postCatchedException(new Throwable("软件安装失败--> 后台MD5：" +
                                mAppBean.getMd5() + "__" + "安装包MD5：" + fileMD5));
                    }
                }

                @Override
                public void onDownloading(String url, int contentLength, int currSize) {
                    double progress = (double) currSize / (double) contentLength;
                    mTextProgress.setText((int) (progress * 100) + " %" + "");
                    mProgressBar.setProgress((int) (progress * 100));
                    LogUtils.e("Download", url + ": " + contentLength + "<->" + currSize);
                    mTips.setText("软件正在更新中，请稍后……");
                }

                @Override
                public void onDownloadStarted(String url, String path, String fileName) {
                    mTips.setText("软件开始下载");
                }

                @Override
                public void onDownloadErr(int code, String url, String error) {
                    mTips.setText("软件下载出错了");
                    CrashReport.postCatchedException(new Throwable("downFail: code is " + code +
                            " url is " + url + " error is " + error));
                }
            });
        }
        File appFilePath = new File(MeiJuLi.Key.PATH_UPDATE_FILE, APP_FILE_NAME);
        if (appFilePath.exists()) {
            appFilePath.delete();
        }

        mDownloader.download(url, MeiJuLi.Key.PATH_UPDATE_FILE, APP_FILE_NAME);
    }

    private void installPkg(String path) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(this,
                    "com.join51.juhuixia.business.fileProvider",
                    new File(path));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        }
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDownloader != null) {
            mDownloader.quit();
        }
    }
}
